/*
  简易前端应用脚本：
  - 读取/写入 localStorage 中的 JWT
  - 登录状态判断与退出
  - 视图切换：home / history / users
  - 加载历史记录与用户管理数据
*/
(function () {
  const API_BASE = '';

  const app = Vue.createApp({
    data() {
      return {
        currentView: 'home',
        isLoggedIn: false,
        token: null,
        // 提问
        isLoading: false,
        askError: '',
        questionForm: { question: '' },
        currentAnswer: null,
        // 历史
        history: [],
        historyPage: { number: 0, totalPages: 0, size: 10, totalElements: 0 },
        historyFilter: { username: '', questionText: '' },
        // 用户管理
        users: { content: [], number: 0, totalPages: 0, totalElements: 0, size: 10 },
        userFilter: { username: '', email: '', isActive: null },
        editDialog: { visible: false, saving: false, error: '', form: { id: '', username: '', email: '', isActive: false } },
        registerDialog: { visible: false, saving: false, error: '', form: { username: '', email: '', password: '' } },
      };
    },
    mounted() {
      const t = localStorage.getItem('jwt_token');
      if (t) {
        this.token = t;
        this.isLoggedIn = true;
      }
    },
    methods: {
      roleLabel(roles) {
        if (!roles || !Array.isArray(roles)) return '普通用户';
        const set = new Set(roles.map(r => String(r).toUpperCase()));
        if (set.has('ADMIN')) return '管理员';
        return '普通用户';
      },
      showHome() { this.currentView = 'home'; },
      showHistory() { this.currentView = 'history'; this.loadHistory(0); },
      showUserMgmt() { this.currentView = 'users'; this.loadUsers(0); },
      logout() {
        localStorage.removeItem('jwt_token');
        this.token = null;
        this.isLoggedIn = false;
        window.location.href = 'login.html';
      },
      openRegister() {
        this.registerDialog.visible = true;
        this.registerDialog.error = '';
        this.registerDialog.form = { username: '', email: '', password: '' };
      },
      closeRegister() {
        this.registerDialog.visible = false;
      },
      async saveRegister() {
        if (!this.token) { return; }
        this.registerDialog.saving = true;
        this.registerDialog.error = '';
        try {
            await axios.post(API_BASE + '/api/auth/signup', {
              username: this.registerDialog.form.username,
              email: this.registerDialog.form.email,
              password: this.registerDialog.form.password
            }, {
              headers: { Authorization: 'Bearer ' + this.token, 'Content-Type': 'application/json' }
            });
            this.registerDialog.visible = false;
            this.loadUsers(0);
        } catch (e) {
            this.registerDialog.error = '注册失败：' + (e.response?.data || e.message);
        } finally {
            this.registerDialog.saving = false;
        }
      },
      formatDate(ts) {
        try { return new Date(ts).toLocaleString(); } catch { return ts; }
      },
      async askQuestion() {
        if (!this.token) { alert('请先登录'); return; }
        this.askError = '';
        this.isLoading = true;
        this.currentAnswer = null;
        try {
          const res = await axios.post(API_BASE + '/api/ask/question',
            { question: this.questionForm.question },
            { headers: { Authorization: 'Bearer ' + this.token } }
          );
          const data = res.data && res.data.data;
          if (data) {
            this.currentAnswer = data;
          }
        } catch (e) {
          this.askError = '提交失败：' + (e.response?.data || e.message);
        } finally {
          this.isLoading = false;
        }
      },
      async loadHistory(page) {
        if (!this.token) { return; }
        try {
          const params = { page: page || 0, size: this.historyPage.size };
          if (this.historyFilter.username) params.username = this.historyFilter.username;
          if (this.historyFilter.questionText) params.questionText = this.historyFilter.questionText;
          const res = await axios.get(API_BASE + '/api/ask/history', {
            headers: { Authorization: 'Bearer ' + this.token },
            params
          });
          const p = res.data && res.data.data;
          const list = (p && p.content) || [];
          this.history = list.map(it => ({
            question: it.questionText,
            answer: it.answerText,
            timestamp: it.createdAt,
            id: it.id,
            username: it.username
          }));
          if (p) {
            this.historyPage.number = p.number || 0;
            this.historyPage.totalPages = p.totalPages || 0;
            this.historyPage.totalElements = p.totalElements || 0;
          }
        } catch (e) {
          console.warn('加载历史失败', e);
          this.history = [];
        }
      },
      historyPrev() {
        if (this.historyPage.number > 0) {
          this.loadHistory(this.historyPage.number - 1);
        }
      },
      historyNext() {
        if (this.historyPage.number + 1 < this.historyPage.totalPages) {
          this.loadHistory(this.historyPage.number + 1);
        }
      },
      async loadUsers(page) {
        if (!this.token) { return; }
        try {
          const params = {
            page: page || 0,
            size: this.users.size || 10,
          };
          if (this.userFilter.username) params.username = this.userFilter.username;
          if (this.userFilter.email) params.email = this.userFilter.email;
          if (this.userFilter.isActive !== null) params.isActive = this.userFilter.isActive;

          const res = await axios.get(API_BASE + '/api/users', {
            headers: { Authorization: 'Bearer ' + this.token },
            params
          });
          this.users = (res.data && res.data.data) || { content: [], number: 0, totalPages: 0, totalElements: 0, size: 10 };
        } catch (e) {
          console.warn('加载用户失败', e);
          this.users = { content: [], number: 0, totalPages: 0, totalElements: 0, size: 10 };
        }
      },
      async toggleUser(u) {
        if (!this.token) { return; }
        try {
          const res = await axios.patch(API_BASE + `/api/users/${u.id}/status`, null, {
            headers: { Authorization: 'Bearer ' + this.token },
            params: { isActive: !u.isActive }
          });
          // 刷新当前页
          this.loadUsers(this.users.number);
        } catch (e) {
          alert('切换用户状态失败：' + (e.response?.data || e.message));
        }
      },
      editUser(u) {
        this.editDialog.visible = true;
        this.editDialog.error = '';
        this.editDialog.form = { id: u.id, username: u.username, email: u.email, isActive: !!u.isActive };
      },
      closeEdit() {
        this.editDialog.visible = false;
      },
      async saveUser() {
        if (!this.token) { return; }
        this.editDialog.saving = true;
        this.editDialog.error = '';
        try {
          const payload = {
            username: this.editDialog.form.username,
            email: this.editDialog.form.email,
            isActive: this.editDialog.form.isActive
          };
          await axios.put(API_BASE + `/api/users/${this.editDialog.form.id}`, payload, {
            headers: { Authorization: 'Bearer ' + this.token }
          });
          this.editDialog.visible = false;
          this.loadUsers(this.users.number);
        } catch (e) {
          this.editDialog.error = '保存失败：' + (e.response?.data || e.message);
        } finally {
          this.editDialog.saving = false;
        }
      }
    }
  });

  app.mount('#app');
})();


